#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QtWidgets>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), timer(new QTimer(this))
    , cells(rows, std::vector<bool>(cols, false))
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 设置中心部件
    centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    setFixedSize(cols * cellSize, rows * cellSize);

    // 初始化细胞状态，例如设置中间区域为活细胞
    for (int i = rows / 4; i < rows * 3 / 4; ++i)
    {
        for (int j = cols / 4; j < cols * 3 / 4; ++j)
        {
            cells[i][j] = true;
        }
    }

    // 连接计时器以驱动生命游戏的迭代
    connect(timer, &QTimer::timeout, this, &MainWindow::nextGeneration);
    timer->start(100);

    // 确保窗口显示时会立即更新以展示初始状态
    update();

}

MainWindow::~MainWindow()
{
    delete ui;
    delete timer;
}

void MainWindow::paintEvent(QPaintEvent * /*event*/)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, false);
    painter.fillRect(rect(), Qt::white);

    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black);
    for (int row = 0; row < rows; ++row) {
        for (int col = 0; col < cols; ++col) {
            if (cells[row][col]) {
                painter.drawRect(col * cellSize, row * cellSize, cellSize, cellSize);
            }
        }
    }
}

void MainWindow::mousePressEvent(QMouseEvent *event)
{
    int x = event->pos().x() / cellSize;
    int y = event->pos().y() / cellSize;
    if (x >= 0 && x < cols && y >= 0 && y < rows) {
        cells[y][x] = !cells[y][x];
        update();
    }
}

void MainWindow::nextGeneration()
{
    std::vector<std::vector<bool>> newCells = cells;
    for (int row = 0; row < rows; ++row) {
        for (int col = 0; col < cols; ++col) {
            int liveNeighbors = countNeighbors(row, col);
            newCells[row][col] = cells[row][col] ? (liveNeighbors == 2 || liveNeighbors == 3) : (liveNeighbors == 3);
        }
    }
    cells.swap(newCells); // 使用swap避免内存重新分配
    update();
}

int MainWindow::countNeighbors(int row, int col) const
{
    int count = 0;
    for (int i = -1; i <= 1; ++i) {
        for (int j = -1; j <= 1; ++j) {
            if (i == 0 && j == 0) continue;
            int r = (row + i + rows) % rows;
            int c = (col + j + cols) % cols;
            count += cells[r][c];
        }
    }
    return count;
}


